import React, {Component} from 'react';
import Taro from '@tarojs/taro';
import {AtIcon, AtTabs} from 'taro-ui'
import {Image, Text, View} from '@tarojs/components'
import {COUPON_USER_LIST, RESOURCE_URL, TARO_ENV} from "../../constants/api";
import {user} from "../../utils/user.service";
import {newHttp} from "../../utils/request";
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import {vcmonitor} from "../../utils/tools";
import './list.scss'

export default class List extends Component {
  tabs = [{title: '未使用', value: 0}, {title: '已使用', value: 1}, {title: '已过期', value: 2}]

  state: {
    curTabIndex: number
    list: object[]
  } = {
    list: [],
    curTabIndex: 0,
  }
  page = 1

  async onReachBottom() {
    if (this.state.list && this.state.list.length > 0) {
      const list = await this.getData(this.page)
      const old = this.state.list
      if (list) {
        this.setState({list: [...old, ...list]})
      }
    }
  }

  async onPullDownRefresh() {
    this.page = 1
    const list = await this.getData(this.page)
    this.setState({list})
    Taro.stopPullDownRefresh()
  }

  async UNSAFE_componentWillMount() {
    const isLogin = await user.checkLogin()
    if (!isLogin) {
      Taro.showToast({
        title: '你还未登录，请登录',
        icon: 'none',
      })
      const timer = setTimeout(() => {
        clearTimeout(timer)
        Taro.switchTab({url: '/pages/my/index/index'})
      }, 1500)
      return
    }
    const list = await this.getData(this.page)
    this.setState({list})
  }

  async componentDidShow() {
    vcmonitor(this)
  }

  async getData(page) {
    Taro.showLoading({title: '加载中...'})
    const {curTabIndex} = this.state
    const list = await newHttp.catchPost(COUPON_USER_LIST, {
      p: page,
      s: 10,
      search_status: this.tabs[curTabIndex].value
    })
    if (list && list.length === 10) {
      this.page++
    }
    Taro.hideLoading()
    return list || []
  }

  tabClick(index) {
    Taro.showLoading({title: '加载中...'})
    this.page = 1
    this.setState({curTabIndex: index, list: []}, async () => {
      const list = await this.getData(this.page)
      this.setState({list})
    })
    Taro.hideLoading()
  }

  goUse(item, flag, e) {
    if (flag !== 0) {
      e.stopPropagation()
      const {curTabIndex} = this.state
      if (!curTabIndex) {
        const url = item.url || '/main/coupon/coupon-goods?id=' + item.id
        Taro.navigateTo({
          url
        })
      } else {
        Taro.showToast({title: `您不能使用${curTabIndex == 1 ? '已使用' : '已过期'}的优惠券`, icon: "none"})
      }
    }
  }

  goto(uuid, flag) {
    if (flag !== 0) {
      Taro.navigateTo({
        url: '/main/coupon/detail?uuid=' + uuid + '&type=1'
      })
    }
  }

  render() {
    const {list, curTabIndex} = this.state;
    return (
      <View className='coupon-root'>
        <GzhAuth />
        <AtTabs tabList={this.tabs} current={curTabIndex} onClick={this.tabClick.bind(this)} />
        {list && list.map((item: any, index) => <View onClick={this.goto.bind(this, item.uuid, item.siteFlag)} key={index}
          className={curTabIndex > 0 ? "item end" : "item"}
        >
          <View className='left'>
            <View className='left-top'>￥<Text>{item.discounts_money}</Text></View>
            <View className='left-bottom'>{!!item.can_use_limit ? `满${item.can_use_limit_money}可用` : '无门槛'}</View>
          </View>
          <View className={`right ${curTabIndex > 0 ? (curTabIndex == 1 ? 'shiyong' : 'guoqi') : ''}`}>
            <View className='right-name'>{item.name}</View>
            <View className='right-yxq'>{item.date_show}</View>
            {!curTabIndex && !!item.isCanToUse &&
              <View onClick={this.goUse.bind(this, item, item.siteFlag)}
                className={item.siteFlag === 0 ? 'right-receive right-receive-dis' : 'right-receive'}
              >立即使用</View>}
            <View className={`right-link ${TARO_ENV + '_right-link'}`}>
              <Text className='left-link-text'>可用站点：{item.can_use_site}</Text>
              <Text className='right-link-text'>使用规则</Text>
              <AtIcon value='chevron-right'
                size='11'
              />
            </View>
          </View>
        </View>)}
        {!list.length && <View className='listNull' style='top: 20% !important;'>
          <Image src={`${RESOURCE_URL}/resources/images/yhqNull.png`} mode='widthFix' />
          <View className='text'>还没有可用优惠券~</View>
        </View>}
      </View>
    )
  }
}
